<template>
  <div class="building-type-selector" name="BuildingTypeSelector">
    <!-- 划分方式选择 -->
    <div class="division-section" name="DivisionSection">
      <h4 class="section-title">选择建筑划分方式</h4>
      
      <el-radio-group v-model="selectedDivision" @change="handleDivisionChange" name="DivisionRadioGroup">
        <el-radio 
          v-for="division in divisionList" 
          :key="division.id" 
          :value="division.id"
          class="division-radio"
          :name="`DivisionRadio_${division.id}`"
        >
          {{ division.categoryName }}
        </el-radio>
      </el-radio-group>
    </div>

    <!-- 具体类型选择 -->
    <div v-if="selectedDivision" class="type-section" name="TypeSection">
      <h4 class="section-title">选择具体类型</h4>
      
      <div class="type-grid" name="TypeGrid">
        <el-checkbox-group v-model="currentDivisionSelectedTypes" @change="handleTypeChange" name="TypeCheckboxGroup">
          <div 
            v-for="type in typeList" 
            :key="type.id" 
            class="type-item-wrapper"
            :name="`TypeItemWrapper_${type.id}`"
          >
            <el-checkbox 
              :value="type.id"
              class="type-checkbox"
              :name="`TypeCheckbox_${type.id}`"
            >
              {{ type.categoryName }}
            </el-checkbox>
            <el-tooltip 
              :content="type.description" 
              placement="top" 
              :show-after="500"
              popper-class="building-type-tooltip"
              :name="`TypeTooltip_${type.id}`"
            >
              <el-icon class="info-icon" :name="`InfoIcon_${type.id}`"><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </el-checkbox-group>
      </div>
    </div>

    <!-- 已选择的类型展示 -->
    <div v-if="allSelectedTypes.length > 0" class="selected-section" name="SelectedSection">
      <h4 class="section-title">已选择的类型</h4>
      <div class="selected-types" name="SelectedTypes">
        <div class="type-tags">
          <el-tag 
            v-for="type in allSelectedTypes" 
            :key="type.id"
            closable
            @close="removeType(type.id, type.parentId)"
            class="selected-tag"
            :name="`SelectedTag_${type.id}`"
          >
            {{ type.categoryName }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 组合结果预览 -->
    <div v-if="allSelectedTypes.length > 0" class="preview-section" name="PreviewSection">
      <h4 class="section-title">组合结果预览</h4>
      <div class="preview-controls">
        <el-input
          v-model="combinedResult"
          type="textarea"
          :rows="3"
          placeholder="建筑类型组合结果将在这里显示，您可以进行编辑"
          class="preview-input"
          name="CombinedResultInput"
          @input="handleCombinedResultEdit"
        />
        <div class="preview-actions">
          <el-button 
            v-if="isUserEdited" 
            type="primary" 
            size="small" 
            @click="resetCombinedResult"
            class="reset-btn"
          >
            重置为自动组合
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { buildingTypeApi, type BuildingTypeCategory } from '@/api/buildingType'

// 定义接口
// 使用从API导入的BuildingTypeCategory接口

interface Props {
  modelValue?: number[]
  maxSelect?: number
}

interface Emits {
  (e: 'update:modelValue', value: number[]): void
  (e: 'change', value: number[], combinedResult: string): void
}

// 定义props和emits
const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  maxSelect: 10
})

const emit = defineEmits<Emits>()

// 响应式数据
const divisionList = ref<BuildingTypeCategory[]>([])
const typeList = ref<BuildingTypeCategory[]>([])
const selectedDivision = ref<number | undefined>(undefined)
// 按划分方式分组存储选择的类型
const selectedTypesByDivision = ref<{ [divisionId: number]: BuildingTypeCategory[] }>({})
const combinedResult = ref<string>('')
// 标记用户是否手动编辑了组合结果
const isUserEdited = ref<boolean>(false)

// 计算属性
// 当前划分方式下已选择的类型ID列表
const currentDivisionSelectedTypes = computed({
  get: () => {
    if (!selectedDivision.value) return []
    const types = selectedTypesByDivision.value[selectedDivision.value] || []
    return types.map(type => type.id)
  },
  set: (value: number[]) => {
    // 这个setter不会被直接调用，通过handleTypeChange处理
  }
})

// 所有已选择的类型
const allSelectedTypes = computed(() => {
  const allTypes: BuildingTypeCategory[] = []
  Object.values(selectedTypesByDivision.value).forEach(types => {
    allTypes.push(...types)
  })
  return allTypes
})

// 获取划分方式名称
const getDivisionName = (divisionId: number) => {
  // 从已加载的划分方式列表中查找
  const division = divisionList.value.find(d => d.id === divisionId)
  if (division) {
    return division.categoryName
  }
  
  // 如果找不到，返回默认名称
  return `划分方式${divisionId}`
}

// 获取划分方式列表
const loadDivisionList = async () => {
  try {
    const response = await buildingTypeApi.getDivisionList()
    if (response.code === 200) {
      divisionList.value = response.data || []
    } else {
      console.error('获取划分方式列表失败:', response.message)
      ElMessage.error('获取划分方式列表失败')
    }
  } catch (error) {
    console.error('加载划分方式列表失败:', error)
    ElMessage.error('加载划分方式列表失败')
  }
}

// 获取具体类型列表
const loadTypeList = async (divisionId: number) => {
  try {
    const response = await buildingTypeApi.getTypeListByDivision(divisionId)
    if (response.code === 200) {
      typeList.value = response.data || []
    } else {
      console.error('获取类型列表失败:', response.message)
      ElMessage.error('获取类型列表失败')
    }
  } catch (error) {
    console.error('加载类型列表失败:', error)
    ElMessage.error('加载类型列表失败')
  }
}

// 处理划分方式变化
const handleDivisionChange = (divisionId: number) => {
  // 不再清空之前的选择，只加载当前划分方式的类型列表
  loadTypeList(divisionId)
}

// 处理类型选择变化
const handleTypeChange = (types: number[]) => {
  if (!selectedDivision.value) return
  
  // 检查总选择数量限制
  const totalSelectedCount = allSelectedTypes.value.length
  const currentDivisionCount = selectedTypesByDivision.value[selectedDivision.value]?.length || 0
  const newCount = types.length
  
  if (totalSelectedCount - currentDivisionCount + newCount > props.maxSelect) {
    ElMessage.warning(`最多只能选择${props.maxSelect}个类型`)
    return
  }
  
  // 更新当前划分方式下的选择
  const selectedTypes = typeList.value.filter(type => types.includes(type.id))
  selectedTypesByDivision.value[selectedDivision.value] = selectedTypes
  
  updateCombinedResult()
  emitChange()
}

// 移除已选择的类型
const removeType = (typeId: number, divisionId: number) => {
  if (selectedTypesByDivision.value[divisionId]) {
    selectedTypesByDivision.value[divisionId] = selectedTypesByDivision.value[divisionId].filter(type => type.id !== typeId)
    
    // 如果该划分方式下没有选择了，删除该分组
    if (selectedTypesByDivision.value[divisionId].length === 0) {
      delete selectedTypesByDivision.value[divisionId]
    }
  }
  
  // 如果用户已经手动编辑过，不自动更新组合结果
  if (!isUserEdited.value) {
    updateCombinedResult()
  }
  emitChange()
}

// 更新组合结果
const updateCombinedResult = () => {
  if (allSelectedTypes.value.length === 0) {
    combinedResult.value = ''
    return
  }
  
  // 按划分方式排序，确保组合结果的一致性
  const sortedDivisions = Object.keys(selectedTypesByDivision.value)
    .map(Number)
    .sort((a, b) => a - b)
  
  const typeNames: string[] = []
  sortedDivisions.forEach(divisionId => {
    const types = selectedTypesByDivision.value[divisionId]
    types.forEach(type => {
      typeNames.push(type.categoryName)
    })
  })
  
  const newCombinedResult = typeNames.join('')
  
  // 如果用户已经手动编辑过，追加新选择的类型
  if (isUserEdited.value) {
    // 检查新选择的类型是否已经存在于编辑内容中
    const currentContent = combinedResult.value
    const newTypes = typeNames.filter(typeName => !currentContent.includes(typeName))
    
    if (newTypes.length > 0) {
      // 将新类型追加到现有内容后面（尾部）
      combinedResult.value = currentContent + newTypes.join('')
    }
  } else {
    // 用户未编辑过，直接更新
    combinedResult.value = newCombinedResult
  }
}

// 处理组合结果的手动编辑
const handleCombinedResultEdit = () => {
  isUserEdited.value = true
  emitChange()
}

// 重置组合结果为自动组合
const resetCombinedResult = () => {
  isUserEdited.value = false
  updateCombinedResult()
  emitChange()
}

// 监听组合结果变化
watch(combinedResult, () => {
  emitChange()
})

// 发送变化事件
const emitChange = () => {
  const allTypeIds = allSelectedTypes.value.map(type => type.id)
  emit('update:modelValue', allTypeIds)
  emit('change', allTypeIds, combinedResult.value)
}

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
  if (newValue && newValue.length > 0) {
    // 根据ID重新构建按划分方式分组的数据
    rebuildSelectedTypesByDivision(newValue)
  } else {
    // 清空所有选择
    selectedTypesByDivision.value = {}
    combinedResult.value = ''
  }
}, { immediate: true })

// 根据ID列表重建按划分方式分组的数据
const rebuildSelectedTypesByDivision = async (typeIds: number[]) => {
  try {
    // 获取所有类型的详细信息
    const response = await buildingTypeApi.getTypeListByIds(typeIds)
    if (response.code === 200 && response.data) {
      const types = response.data
      
      // 按划分方式分组
      const grouped: { [divisionId: number]: BuildingTypeCategory[] } = {}
      types.forEach(type => {
        const divisionId = type.parentId
        if (!grouped[divisionId]) {
          grouped[divisionId] = []
        }
        grouped[divisionId].push(type)
      })
      
      selectedTypesByDivision.value = grouped
      
      // 重建数据时，如果用户没有手动编辑过，则更新组合结果
      if (!isUserEdited.value) {
        updateCombinedResult()
      }
    } else {
      console.error('重建选择数据失败:', response.message)
      ElMessage.error('重建选择数据失败')
    }
  } catch (error) {
    console.error('重建选择数据失败:', error)
    ElMessage.error('重建选择数据失败')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadDivisionList()
})
</script>

<style scoped>
.building-type-selector {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-left: 4px solid #409eff;
  padding-left: 12px;
}

.division-section {
  margin-bottom: 24px;
}

.division-radio {
  margin-right: 20px;
  margin-bottom: 12px;
}

.division-radio :deep(.el-radio__label) {
  font-size: 14px;
  color: #606266;
}

.type-section {
  margin-bottom: 24px;
}

.type-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 12px;
}

.type-item-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.type-checkbox {
  margin-right: 0;
}

.type-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.type-name {
  font-size: 14px;
  color: #606266;
}

.info-icon {
  color: #909399;
  font-size: 16px;
  cursor: pointer;
  transition: color 0.3s;
}

.info-icon:hover {
  color: #409eff;
}

.selected-section {
  margin-bottom: 24px;
}

.selected-types {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.type-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-tag {
  margin: 0;
}

.preview-section {
  margin-bottom: 24px;
}

.preview-controls {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.preview-input {
  width: 100%;
}

.preview-input :deep(.el-textarea__inner) {
  font-size: 14px;
  line-height: 1.5;
}

.preview-actions {
  display: flex;
  justify-content: flex-end;
}

.reset-btn {
  font-size: 12px;
  padding: 6px 12px;
}

/* 工具提示样式 */
:deep(.building-type-tooltip) {
  max-width: 300px;
  font-size: 12px;
  line-height: 1.4;
}
</style>
